import jwt
import time
from datetime import datetime

"""
pip install pyJWT==2.8.0
"""

SECRET_KEY = "%^ES*E&Ryurehuie9*7^%$#$EDFGHUYTRE#$%^&%$#@#$RTYGHIKS%TWHJYS&"
DEFAULT_EXP = 7 * 24 * 60 * 60


def create_token(username: str, timeout=DEFAULT_EXP):
    """
    :param username: 特殊字符串
    :param timeout: token有效时间，默认是一天
    :return:
    """

    if not isinstance(timeout, int):
        # 传递的类型有误，使用配置中的时间戳
        timeout = DEFAULT_EXP
    # 构造header
    headers = {"type": "jwt", "alg": "HS256"}
    # 缓存数据
    this_time = time.time()
    this_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    payload = {"username": username, "exp": this_time + timeout,"create_time":this_datetime}

    token = jwt.encode(
        payload=payload, key=SECRET_KEY, algorithm="HS256", headers=headers
    )
    if isinstance(token, bytes):
        token = token.decode("utf-8")
    return token


# 给websocket发起连接时，验证token
def decode_token(token: str):
    # 加密用的盐
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        exp_time = payload.get("exp")
        username = payload.get("username")
        now_time = time.time()
        if now_time > exp_time:
            # token已经过期
            return False, "token已经过期"
        else:
            return True, (username, exp_time)
    except Exception:
        return False, "非法的token"


if __name__ == "__main__":
    token = create_token("gzgs")
    print(token, len(token))
    ret = decode_token(token)
    print(ret)
